package com.example.movie.mate.config;

import com.example.movie.mate.interceptor.AdminInterceptor;
import com.example.movie.mate.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    // 配置跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    // 注册自定义的转换器：将String类型的yyyy-MM-dd HH:mm:ss格式的日期转换成LocalDateTime
    // 注册自定义的转换器：将String类型的yyyy-MM-dd格式的日期转换成LocalDate
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, LocalDate>() {
            private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            @Override
            public LocalDate convert(String source) {
                return LocalDate.parse(source, FORMATTER);
            }
        });
        registry.addConverter(new Converter<String, LocalDateTime>() {
            private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            @Override
            public LocalDateTime convert(String source) {
                return LocalDateTime.parse(source, FORMATTER);
            }
        });
    }

    // Session拦截器
    @Autowired
    private LoginInterceptor loginInterceptor;
    // 管理员拦截器
    @Autowired
    private AdminInterceptor adminInterceptor;

    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePathPatterns = new ArrayList<>();
        excludePathPatterns.add("/doc.html"); // Knife4j相关文件
        excludePathPatterns.add("/webjars/**"); // Knife4j相关文件
        excludePathPatterns.add("/v3/api-docs/**"); // Knife4j相关文件
        excludePathPatterns.add("/favicon.ico"); // Knife4j相关文件
        excludePathPatterns.add("/api/*/public/**");

        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**") // 添加需要拦截的URL路径
                .excludePathPatterns(excludePathPatterns); // 添加不需要拦截的URL路径

        registry.addInterceptor(adminInterceptor)
                .addPathPatterns("/api/*/manage/**"); // 添加需要拦截的URL路径
    }

}
